<template>
	<div class="variable-judge-input-container">
		<p class="setting" v-if="!showDetail">
			<el-button class="" @click="addJudeBranch" v-if="isShowJudge && !showDetail && form.variableBranchList.length === 0">新增一个判断分支</el-button>
		</p>
		<div class="answer-branch" v-for="(item, index) in form.variableBranchList" :key="index">
			<p class="branch-text">分支{{ getBranchIndex(index) }}</p>
			<el-form-item label-width="10px">
				<el-select v-model="item.rule" placeholder="请选择分支条件" class="enumeration-select" :disabled="showDetail">
					<el-option v-for="v in enumerationList" :key="v.value" :label="v.label" :value="v.value"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item :label="'判断条件' + getBranchIndex(conditionsIndex)" v-for="(data, conditionsIndex) in item.conditions" :key="conditionsIndex + data.id" label-width="120px" style="display: flex; flex-direction: column;">
				<VariableSelectSingle
					:prop="`${prop}.${index}.conditions.${conditionsIndex}.inputText`"
					:roleData="roleData"
					:describeList="describeList"
					:businessData="businessData"
					:condition="data"
					:rules="rules"
					:showDetail="showDetail"
					@change="
						checken => {
							onChange(`variableBranchList.${index}.conditions.${conditionsIndex}.inputText`, index);
							onBlurEqual({ inputText: checken.inputText, index, conditionsIndex, rule: data.rule, data: checken });
						}
					"
				/>
				<el-form-item :prop="`${prop}.${index}.conditions.${conditionsIndex}.rule`" :rules="rules.rule" style="width: 110px;">
					<el-select
						v-model="data.rule"
						placeholder="请选择变量判断条件"
						@change="
							checken => {
								onChange(`variableBranchList.${index}.conditions.${conditionsIndex}.rule`, index);
								// onChange(`variableBranchList.${index}.conditions`);
								variableDescChange({ disabled: data.variableDesc, rule: data.rule, index, conditionsIndex });
							}
						"
						:disabled="showDetail"
						:popper-append-to-body="false"
						size="mini"
					>
						<div v-if="data.variableType === 'text'">
							<el-option v-for="k in textVariableList" :key="k.value" :label="k.label" :value="k.value"> </el-option>
						</div>
						<div v-else>
							<el-option v-for="k in conditionList" :key="k.value" :label="k.label" :value="k.value"> </el-option>
						</div>
					</el-select>
				</el-form-item>
				<el-form-item v-show="['eq', 'ne'].includes(data.rule)">
					<el-checkbox
						v-model="data.variableDesc"
						@change="
							checken => {
								variableDescHandle({ checken, index, conditionsIndex });
							}
						"
						size="mini"
						style="width: 100px;"
						>变量值为空</el-checkbox
					>
				</el-form-item>
				<el-form-item :prop="`${prop}.${index}.conditions.${conditionsIndex}.value`" :rules="data.variableDesc ? '' : rules.value">
					<el-input
						v-model="data.value"
						placeholder="请输入变量判断值"
						@change="
							checken => {
								onChange(`variableBranchList.${index}.conditions.${conditionsIndex}.value`, index);
								// onChange(`variableBranchList.${index}.conditions`);
							}
						"
						maxlength="50"
						:disabled="showDetail || data.variableDesc"
					></el-input>
				</el-form-item>
				<i class="el-icon-close delIcon" @click="reomveJudgement(index, conditionsIndex)" v-show="isActiveIcon && item.conditions.length > 1 && !showDetail"></i>
			</el-form-item>
			<p class="add-condition" @click="addCondition(index)" v-show="isActiveIcon && item.conditions.length !== 5 && !showDetail"> + 添加条件 </p>
			<el-form-item label="下一步" :prop="`${prop}.${index}.nextStepsAnswer`" class="netText-label" style="margin-top: 15px" :rules="rules.nextStepsAnswer">
				<el-select v-model="item.nextStepsAnswer" placeholder="下一步操作" @change="onChange(`variableBranchList.${index}.nextStepsAnswer`, index)" :disabled="showDetail">
					<el-option v-for="item in nextStepOption" :key="item.value" :label="item.taskName" :value="item.taskId"> </el-option>
				</el-select>
			</el-form-item>
			<div class="btn" v-if="!showDetail">
				<img @click="deleteBranch(index)" class="del-btn" :src="deleteImage" />
				<img @click="addBranch" class="add-btn" :src="insertImage" v-show="isActiveIcon && index === form.variableBranchList.length - 1 && index !== 5" />
			</div>
		</div>
	</div>
</template>

<script>
import { getAllRole, getBusinessVariables, getVariablesAll } from '@/api/api.js';
import VariableSelectSingle from './VariableSelectSingle.vue';
import delGroupImg from '@/assets/img/icon/del_group.png';
import addGroupImg from '@/assets/img/icon/add_group.png';
export default {
	name: '',
	components: { VariableSelectSingle },
	props: {
		nextStepOption: {
			type: Array,
			default: () => [],
			required: true
		},
		prop: {
			type: String,
			default: () => ''
		},
		value: {
			type: Array,
			required: true,
			default: () => []
		},
		showDetail: {
			type: Boolean,
			default: () => false
		}
	},
	data() {
		const validateName = (rules, values = [], callback) => {
			console.warn('validateName', values);
			const currentArr = values.filter(currentValue => {
				console.log('currentValue', currentValue);
				const { inputText = '', rule = '', value = '', variableDesc = '' } = currentValue;
				if (inputText === '' || rule === '' || (!variableDesc && value === '')) {
					return true;
				}
			});
			console.log('currentArr', currentArr);
			if (currentArr.length > 0) {
				return callback(new Error('请编辑判断条件'));
			}
			return callback();
		};

		return {
			form: {
				variableBranchList: [] //外层判断分支列表
			},
			deleteImage: delGroupImg,
			insertImage: addGroupImg,
			isShowJudge: true, //新增一个判断分支按钮显示隐藏
			isShowAnswerBranch: false, //分支内容显示隐藏
			isActiveIcon: true, // icon图标显示隐藏
			// 条件枚举 and  or
			enumerationList: [
				{ label: 'and', value: 'and' },
				{ label: 'or', value: 'or' }
			],
			describeList: [], //变量描述下拉框列表数据
			// 变量判断条件列表
			conditionList: [
				{ label: '==', value: 'eq' },
				{ label: '! =', value: 'ne' },
				{ label: '>', value: 'gt' },
				{ label: '<', value: 'lt' },
				{ label: '>=', value: 'gte' },
				{ label: '<=', value: 'lte' }
			],
			// 对于“文本/字符串”类变量仅（展示）支持选择“==”和“！=”；“数值”类变量可（展示）选择全部
			textVariableList: [
				{ label: '==', value: 'eq' },
				{ label: '! =', value: 'ne' }
			],
			rules: {
				inputText: [
					{
						required: true,

						message: '请编辑判断条件',
						trigger: 'blur'
					}
				],
				rule: [
					{
						required: true,

						message: ' ',
						trigger: 'blur'
					}
				],
				value: [
					{
						required: true,

						message: ' ',
						trigger: 'blur'
					}
				],
				nextStepsAnswer: [
					{
						required: true,
						message: '请选择下一步操作',
						trigger: 'change'
					}
				],
				conditions: [
					{
						required: true,
						validator: validateName
					}
				]
			},
			roleData: [],
			activeName: 'customer',
			activeTag: 1,
			scenId: JSON.parse(sessionStorage.getItem('sceneData'))?.id || this.$route.params.scenId,
			pageData: {
				page: 1,
				pageSize: 100000,
				total: 0
			},
			businessData: []
		};
	},
	watch: {
		value(val) {
			this.form.variableBranchList = [...val];
		}
	},
	mounted() {
		this.initAllRole();
		this.initBusinessData();

		let variables = [...this.form.variableBranchList, ...this.value];
		if (variables?.length > 0) {
			this.form.variableBranchList = variables;
		}
	},
	methods: {
		// 新增一个判断分支
		addJudeBranch() {
			const { form: { variableBranchList = [] } = {} } = this;
			this.isShowAnswerBranch = true;
			this.isShowJudge = false;
			if (variableBranchList.length === 0) {
				this.addBranch();
			}
		},
		// + icon 添加分支
		addBranch() {
			const { form: { variableBranchList = [] } = {} } = this;
			let branch = {
				do: {
					command: 'jump-to',
					id: '',
					no: ''
				},
				rule: 'and',
				conditions: [
					{
						inputText: '',
						id: '',
						variableType: '',
						initMode: '',
						name: '',
						rule: '',
						value: '',
						url: '',
						method: '',
						params: ''
					}
				],
				nextStepsAnswer: ''
			};
			variableBranchList.push(branch);
			this.$emit('input', this.prop, variableBranchList);
		},
		//  - icon 删除分支
		deleteBranch(index) {
			const { form: { variableBranchList = [] } = {} } = this;
			if (variableBranchList.length - 1 === 0) {
				this.isShowJudge = true;
				this.isShowAnswerBranch = false;
			}
			variableBranchList.splice(index, 1);
			this.$emit('input', this.prop, variableBranchList);
		},
		// 获取返回分支下标 例如：分支一
		getBranchIndex(value) {
			let result = '';
			switch (value) {
				case 0:
					result = '一';
					break;
				case 1:
					result = '二';
					break;
				case 2:
					result = '三';
					break;
				case 3:
					result = '四';
					break;
				case 4:
					result = '五';
					break;
				case 5:
					result = '六';
					break;
				default:
					result = '';
					break;
			}
			return result;
		},
		// 变量为空 清空 变量判断值
		variableDescHandle(e) {
			const { checken, index, conditionsIndex } = e;
			const { form: { variableBranchList = [] } = {} } = this;
			if (checken) {
				variableBranchList[index].conditions[conditionsIndex].value = '';
				this.$emit('input', this.prop, variableBranchList);
			}
		},
		// variableType !== 'text' 时
		variableDescChange(e) {
			const { disabled, rule, index, conditionsIndex } = e;
			const { form: { variableBranchList = [] } = {} } = this;
			if (disabled && !['eq', 'ne'].includes(rule)) {
				variableBranchList[index].conditions[conditionsIndex].variableDesc = false;
				this.$emit('input', this.prop, variableBranchList);
			}
		},
		// 添加条件
		addCondition(index) {
			const { form: { variableBranchList = [] } = {} } = this;
			const conditions = {
				inputText: '',
				variableType: '',
				initMode: '',
				name: '',
				rule: '',
				value: '',
				url: '',
				method: '',
				params: ''
			};
			variableBranchList[index].conditions.push(conditions);
			this.$emit('input', this.prop, variableBranchList);
		},
		// 删除判断条件
		reomveJudgement(index, conditionsIndex) {
			console.log('reomveJudgement ', index, conditionsIndex);
			const { form: { variableBranchList = [] } = {} } = this;
			variableBranchList[index].conditions.splice(conditionsIndex, 1);
			this.$emit('input', this.prop, variableBranchList);
		},

		// 请选择变量描述
		onBlurEqual({ inputText, index, conditionsIndex, rule = '', data }) {
			console.log('请选择变量描述 =>onBlurEqual', inputText, index, conditionsIndex, rule, data);
			this.inputText = inputText;
			const { form: { variableBranchList = [] } = {}, describeList = [], businessData = [] } = this;
			variableBranchList[index].conditions[conditionsIndex].inputText = inputText;
			// variableJudgeOptions.0.conditions.0.inputText
			if (data.activeName === 'business') {
				console.log(this.activeName, inputText.split('-')[1]);
				const current = businessData.find(item => item.id === data.id);
				const { type = '' } = current;
				console.log('current', current, 'type', type);
				if (!(('eq,ne'.includes(rule) && type === 'text') || ('eq,ne,gt,gte,lte'.includes(rule) && type === 'numeric'))) {
					variableBranchList[index].conditions[conditionsIndex].rule = '';
				}
				variableBranchList[index].conditions[conditionsIndex].variableType = type;
				variableBranchList[index].conditions[conditionsIndex].initMode = current.initMode || '';
				variableBranchList[index].conditions[conditionsIndex].id = current.id || '';
				variableBranchList[index].conditions[conditionsIndex].method = current.method || '';
				variableBranchList[index].conditions[conditionsIndex].name = current.name || '';
				return type;
			}
			if (data.activeName === 'customer') {
				const current = describeList.find(item => item.id === data.id);
				const { type = '' } = current;
				console.log('current', current, 'type', type);
				if (!(('eq,ne'.includes(rule) && type === 'text') || ('eq,ne,gt,gte,lte'.includes(rule) && type === 'numeric'))) {
					variableBranchList[index].conditions[conditionsIndex].rule = '';
				}
				variableBranchList[index].conditions[conditionsIndex].variableType = type;
				variableBranchList[index].conditions[conditionsIndex].initMode = current.initMode || '';
				variableBranchList[index].conditions[conditionsIndex].id = current.id || '';
				variableBranchList[index].conditions[conditionsIndex].method = current.method || '';
				variableBranchList[index].conditions[conditionsIndex].name = current.name || '';
				return type;
			}
		},

		onChange(val, index) {
			this.form.variableBranchList[index].do.id = this.form.variableBranchList[index].nextStepsAnswer;
			this.form.variableBranchList[index].do.no = this.form.variableBranchList[index].nextStepsAnswer;
			this.$emit('input', this.prop, this.form.variableBranchList);
		},
		// 初始化所有角色
		initAllRole() {
			getAllRole(this.scenId)
				.then(res => {
					this.roleData = res.data.data;
					this.activeTag = res.data.data[0]?.id;
					// }
					this.getVariablesAll();
				})
				.catch(err => {
					console.log(err);
				});
		},
		// 客户信息变量配置初始化
		initBusinessData() {
			getBusinessVariables({ scenId: this.scenId, page: 1, pageSize: 1000 })
				.then(res => {
					console.log(res.data.data, '业务信息变量');
					this.businessData = res.data.data.data;
				})
				.catch(err => {
					console.log(err);
					this.$message.error('获取客户信息变量列表失败！');
				});
		},
		checkRole(id) {
			this.activeTag = id;
		},
		filterCheckCustomer(inputText) {
			let result = this.describeList.filter(item => item.name === inputText);
			// console.log(result, 'getSelectVariable:');
			return `客户信息-${result[0].roleName}-${result[0].name}`;
		},
		getVariablesAll() {
			let param = {
				scenId: this.scenId,
				page: 1,
				pageSize: 10000
			};
			getVariablesAll(param)
				.then(res => {
					if (res.data.data && res.data.data.rows) {
						res.data.data.rows.map(item => {
							if (item.roleId) {
								const data = {
									id: item.id,
									name: item.name,
									roleId: item.roleId,
									dataMasking: item.dataMasking,
									params: item.params,
									url: item.url,
									method: item.method,
									linkedKey: item.linkedKey,
									isDefault: item.isDefault,
									key: item.name,
									property: item.type,
									content: '',
									initMode: item.initMode,
									scenId: this.scenId,
									roleName: item.bizscenario_role.name,
									type: item.type
								};
								this.describeList.push(data);
							}
						});
						this.pageData.total = res.data.data.count;
					} else {
						console.warn('get variable list error ', res.data);
					}
				})
				.catch(err => {
					console.log(err);
					this.$message.error('获取客户信息变量列表失败！');
				});
		}
	}
};
</script>

<style lang="less" scoped>
.variable-judge-input-container {
	.el-checkbox {
		// padding: 0 10px;
		margin-right: 10px;
	}
	.setting {
		position: relative;
		width: 90%;
		padding: 14px;
		text-align: left;
		left: 0;
		right: 0;
		.el-button {
			background-color: #fff;
			border: 1px solid #6384fe;
			color: #6384fe;
		}
	}
	.answer-branch {
		background-color: #f9f9f9;
		margin-top: 15px;
		position: relative;
		padding: 10px 0;
		margin-right: 10px;
		.branch-text {
			font-size: 12px;
			font-family: PingFang SC;
			font-weight: 400;
			color: #333333;
			margin-left: 20px;
		}
		.el-select.enumeration-select {
			width: 20%;
		}
		.add-btn {
			position: absolute;
			bottom: 0;
			right: -18px;
			cursor: pointer;
		}
		.del-btn {
			position: absolute;
			top: 0;
			right: -18px;
			cursor: pointer;
		}
		.add-condition {
			width: 80px;
			font-size: 12px;
			font-family: PingFang SC;
			font-weight: 400;
			color: #6384fe;
			cursor: pointer;
			margin-left: 20px;
			margin-bottom: 10px;
		}
		.delIcon {
			width: 10px;
			height: 10px;
			color: #8d8d92;
			margin-top: 10px;
			font-size: 16px;
			cursor: pointer;
		}
	}
	/deep/ .el-tabs__nav-wrap::after {
		background-color: none !important;
		position: relative;
		height: 0;
	}

	/deep/ .el-form-item__content {
		margin-left: 10px !important;
	}
}
</style>
<style lang="less">
.answer-branch .varscrollSelect .el-select__tags {
	max-height: 231px;
	width: 100%;
	overflow-y: auto;
}
.answer-branch .varscrollSelect .el-select-dropdown__list {
	width: 641px;
}
.variable-judge-customer-text {
	margin-left: 17px;
}

.answer-branch .el-tabs__active-bar {
	background-color: #6384fe !important;
	width: 56px !important;
}
.answer-branch .el-tabs__item {
	font-size: 15px;
	font-family: PingFang SC;
	font-weight: 400;
	color: #b7b7b7 !important;
}
.answer-branch .el-tabs__item.is-active {
	color: #6384fe !important;
}

.answer-branch .el-tabs__nav-wrap::after {
	background-color: none !important;
	position: relative;
	height: 0;
}
</style>
<style>
.variable-judge-role-box {
	display: flex;
}
.variable-judge-role-box .role-text {
	font-size: 13px;
	font-family: PingFang SC;
	font-weight: 400;
	color: #999999;
}
.variable-judge-role-box .role-tag {
	border: 1px solid #c9def8;
	height: 32px;
	background: #ffffff !important;
	border-radius: 4px;
	color: #6784f2 !important;
	margin: 0 7px;
	cursor: pointer;
}
.variable-judge-role-box .activeTag {
	border: 1px solid #c9def8;
	height: 32px;
	border-radius: 4px;
	background: #e7f2fe !important;
	color: #5374f2 !important;
	margin: 0 7px;
	cursor: pointer;
}
</style>
